<?php
namespace Tlf\User;
/**
* Simple way to setup a user login system on a website
*/
class EasyServer {
protected \Lia $lia;
protected \Lia\Package\Server $user_package;
protected \Tlf\User\Lib $lib;
protected \Tlf\User $active_user;
/**
*
* @param string $initialization_pin_file absolute path. must contain a string of 20+ charachters which will be entered to verify the user for initial setup.
* @param string $config_file absolute path. May contain json configs or be nonexistent. An existent file with invalid json will error.
* @param array $db database settings `db`, `host`, `user`, and `password` (prefix each with `user.`
*/
public function __construct(\Lia $lia,string $initialization_pin_file,string $config_file, array $db){
$this->lia = $lia;
$user_lib_dir = dirname(__DIR__);
$configs = [];
if (is_file($config_file)){
$configs = json_decode(file_get_contents($config_file),true);
if (!is_array($configs)){
$msg = "ERROR: User config file does not contain valid json.";
echo $msg;
throw new \Exception($msg);
}
}
$configs = array_merge(
[ // defaults
'user.base_url' => '/user/',
'user.web_address' => 'https://example.com',
'user.email_from' => 'noreply@example.com',
'user.disabled_pages' => [], // One of 'login', 'register', 'reset-password', 'logout', or 'terms'
],
$configs
);
// set the base url for the user pages
$lia->set('user.base_url', $configs['user.base_url']);
// init the user server
$user_package = new \Lia\Package\Server($lia, 'user', $user_lib_dir);
// load db settings from env file & make pdo
$pdo = new \PDO(
"mysql:dbname=".$db['user.db']
.';host='.$db['user.host']
,$db['user.user']
,$db['user.password']
);
$lib = new \Tlf\User\Lib($pdo);
$user_package->lib = $lib;
$lib->config = [
'web_address'=> $configs['user.web_address'],
'email_from'=> $configs['user.email_from'],
];
$lib->disabled_pages = [
$configs['user.disabled_pages'],
];
// passes the user & library to user pages (login, register, etc)
$user_package->public_file_params = [
'lib'=>$lib,
'initialization_pin_file'=>$initialization_pin_file,
];
$lia->addon('lia:server.server')->useTheme = false;
}
public function get_user(): \Tlf\User {
if (isset($this->active_user))return $this->active_user;
// configure the user login library
// log the user in
$current_user = $this->lib->user_from_cookie();
// if there was no cookie, we'll use an unregistered user
if ($current_user===false)$current_user = new \Tlf\User($this->lib->pdo);
$this->user_package->public_file_params['user'] = $current_user;
return $current_user;
}
/**
* let the library handle head,body. It's not styled.
*/
public function enable_full_page(){
$this->lia->addon('lia:server.server')->useTheme = true;
}
}